package snsdbook.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.SQLUtil;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username_field");
    String password = request.getParameter("password_field");
    
    // Check username exists and password equality
    String[] res = SQLUtil.Query("SELECT password FROM users WHERE username='" + username + "'");
    if (res.length == 1 && res[0].equals(password)) {
      // OK
      request.getSession().setAttribute("username", username);
      response.sendRedirect("Profile?username=" + username);
    } else {
      // Login Failed
      response.sendRedirect("Index");
    }
	}
}
